package com.lin.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.lin.pojo.User;
import com.lin.service.user.UserServiceImpl;
import com.lin.util.Constant;
import com.lin.util.PageSupport;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getParameter("method").equals("pwdmodify")){
            this.modifyPassword(req,resp);
        }else  if (req.getParameter("method").equals("savepwd")){
            this.savepwd(req,resp);
        }else if (req.getParameter("method").equals("query")){
            this.query(req,resp);
        }
    }

    //用户列表
    public void query(HttpServletRequest req, HttpServletResponse resp) {
        String queryname = req.getParameter("queryname");
        String queryUserRole = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRoleInt = 0;
        int currentPageNo = 1;
        int pageSize = Constant.pageSize;

        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;

        if(queryname == null){
            queryname = "";
        }
        if(queryUserRole != null && !queryUserRole.equals("")){
            queryUserRoleInt = Integer.parseInt(queryUserRole);
        }
        if(pageIndex != null) {
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取总条数
        int totalCount =userService.getUserCount(queryname, queryUserRoleInt);

        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount =pageSupport.getTotalPageCount();//总共有几页
        if(currentPageNo < 1) {
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount) {//如果页面大于了最后一页就显示最后一页
            currentPageNo =totalPageCount;
        }

        userList = userService.getUserList(queryname, queryUserRoleInt, currentPageNo, pageSize);
        //赋值给jsp页面
        req.setAttribute("userList", userList);

        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("queryUserName", queryname);
        req.setAttribute("queryUserRole", queryUserRoleInt);

        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //修改密码
    public void savepwd(HttpServletRequest req, HttpServletResponse resp) {
        String newpassword = req.getParameter("newpassword");
        Object o = req.getSession().getAttribute(Constant.SESSION_NAME);
        boolean b = false;
        if (null != o && newpassword != null){
            UserServiceImpl userService = new UserServiceImpl();
            b = userService.modifyPassword(((User) o).getId(), newpassword);
            if (b){
                //清空session
                req.getSession().removeAttribute(Constant.SESSION_NAME);
                req.setAttribute("message","密码修改成功，请退出，使用新密码登录");
            }else{
                req.setAttribute("message","密码修改失败");
            }
        }else{
            req.setAttribute("message","新密码有问题");
        }

        try {
            req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //验证旧密码是否一致
    public void modifyPassword(HttpServletRequest req, HttpServletResponse resp) {
        Object o = req.getSession().getAttribute(Constant.SESSION_NAME);
        String oldpassword = req.getParameter("oldpassword");
        User user = (User) o;
        HashMap<String, String> map = new HashMap<String, String>();
        if (o == null){
            //session失效
            map.put("result","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){
            //密码为空
            map.put("result","error");
        } else if (!user.getUserPassword().equals(oldpassword)){
            //密码不一致
            map.put("result","false");
        }else{
            map.put("result","true");
        }
        PrintWriter out = null;

        try {
            resp.setContentType("application/json");
            out = resp.getWriter();
            out.write(JSONArray.toJSONString(map));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            out.flush();
            out.close();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
